
var thread = $('.chat-thread')
var savedUrl = localStorage.getItem("url")
var url = savedUrl == null ? "https://dh.eaxi.com/smsproxy" : savedUrl
var messageID = 10000;
// thread.css({ 'min-height': $(window).height() })

log('系统消息', '欢迎使用短信转发神器，这个应用可以帮你将本机收到的短信转发到服务器上，让您在全球各地随时随地访问！无需开通漫游服务！数据仅存储在内存，退出程序会自动删除，非常安全。')
log('系统消息', '当前服务器地址为：' + url)
log('系统信息', '发送短信到本手机即可修改。短信格式：【SPURL=http://new.url.domain.com】')

window.addEventListener('error', function(e) {
    var ie = window.event || {};
    var errMsg = e.message || ie.errorMessage || "404 error on " + window.location;
    var errSrc = (e.filename || ie.errorUrl) + ': ' + (e.lineno || ie.errorLine);
    log(errMsg, errSrc)
}, true);

pollMessage()
setInterval(function() {
  // location.reload()
  pollMessage()
}, 10000)


function uploadMessage(sender, body) {
  if (body.substring(0, 10) == 'SPURL=http') {
    url = body.substring(6)
    localStorage.setItem("url", url)
    log('系统消息', '服务器链接已经修改成功，新地址为'+url);
    return
  }
  var lastLog = log(sender, body)
  var time = new Date().getTime()
  var fullURL = url + '/index.php'
  $.post(fullURL, {
    sender: sender, time: time, body: body
  }, function(res) {
    showResult(lastLog, true)
    console.log(res)
  }, 'JSON').fail(function(xhr, status, error) {
    showResult(lastLog, false)
    log('error', '消息上传时出错: <br>URL='+fullURL+', <br>ERROR=' + xhr.status + ', '+xhr.statusText)
  })
}

function pollMessage() {
  var fullURL = url + '/poll.php'
  $.get(fullURL, function(data) {
    data = data.replace(/^\s+|\s+$/g, '')
    if (!data) return;
    var arr = data.split("\n");
    if (arr.length < 2) return;
    var to = arr[0]
    var body = arr[1]
    if (typeof SmsProxy !== 'undefined') SmsProxy.sendSms(to, body);
    log(to, body, 'mine')
  }).fail(function(xhr, status, error) {
    log('error', '无法获取待发送信息: <br>URL='+fullURL+', <br>ERROR=' + xhr.status + ', '+xhr.statusText, 'mine')
  })
}

function strip(html)
{
   var tmp = document.createElement("DIV");
   tmp.innerHTML = html;
   return tmp.textContent || tmp.innerText || "";
}

function log(s, b, w) {
  var t = now()
  if (w == 'mine') {
    thread.append('<li class="meta_mine">TO: '+s+'<br>' + t + '</li>');
    thread.append('<li class="bubble mine"><span class="body '+s+'">'+b+'</span></li>');
  } else {
    thread.append('<li class="meta">FROM: '+s+'<br>' + t + '</li>');
    thread.append('<li class="bubble their"><span class="body '+s+'" id=msg_'+messageID+'>'+b+'</span></li>');
  }
  setTimeout(function() {window.scrollBy(0, 800);}, 500)
  
  return messageID++
}

function showResult(msgId, success) {
  $('#msg_'+msgId).addClass(success ? 'success' : 'error')
}

function now() {
  var d = new Date()
  return d.getFullYear() + '-'
    + (1+d.getMonth()) + '-'
    + d.getDay() + ' '
    + d.getHours() + ':'
    + d.getMinutes() + ':'
    + d.getSeconds();
}
